package com.ys.otms.utils;

import com.ys.otms.constant.ThirdConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class ShipXyAPIUtil {

    //船舶搜索是通过已知的船舶某些参数，来获取船舶 ShipID 的数据接口。
    public static JSONObject queryShip(JSONObject obj) {
        String kw = JsonUtil.getJSONObjectString(obj, "keyword");
        if (StringUtil.isEmpty(kw)) {
            JSONObject objRet = new JSONObject();
            objRet.put("msg","查询条件为空！");
            return objRet;
        }
        String url = ThirdConstant.QUERY_URL.replaceAll("keyword", kw)
                .replaceAll("key", ThirdConstant.KEY);

        JSONObject jsonObject = HttpUtil.get(url);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (jsonArray.size() == 0) {
            return null;
        }
        JSONObject retObj = (JSONObject) jsonArray.get(0);

        return retObj;
    }

    public static JSONObject queryManyShip(JSONObject obj) {
        String kw = JsonUtil.getJSONObjectString(obj, "keyword");
        if (StringUtil.isEmpty(kw)) {
            JSONObject objRet = new JSONObject();
            objRet.put("msg","查询条件为空！");
            return objRet;
        }
        String url = ThirdConstant.QUERY_URL.replaceAll("keyword", kw)
                .replaceAll("key", ThirdConstant.KEY);

        JSONObject jsonObject = HttpUtil.get(url);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (jsonArray.size() == 0) {
            return null;
        }
        JSONObject retObj = new JSONObject();

        JSONArray jsonArray1 = new JSONArray();
        //只显示来自船名搜索的数据
        for(int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            if ("1".equals(object.getString("MatchType"))) {
                jsonArray1.add(object);
            }
        }
        retObj.put("jsonArray",jsonArray1);

        return retObj;
    }

    //单船查询是已知船舶的 ShipID 之后，进行单船船位获取的方式
    public static JSONObject getSingleShip(JSONObject obj) {
        String shipId = JsonUtil.getJSONObjectString(obj, "ShipID");
        if(StringUtil.isEmpty(shipId)) {
            return null;
        }
        String url = ThirdConstant.GET_SINGLE_URL.replaceAll("shipId",shipId)
                .replaceAll("key", ThirdConstant.KEY);
        JSONObject jsonObject = HttpUtil.get(url);
        if (!"0".equals(jsonObject)) {
            return null;
        }
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (jsonArray.size() == 0) {
            return null;
        }
        JSONObject retObj = (JSONObject) jsonArray.get(0);
        return retObj;
    }

    //多船查询是一次请求多条船舶的数据，可以每次请求几条，几十条船的数据。
    //注：由于大量并发请求数据，容易造成船讯网服务器通信的压力，所以多船查询的上线是100 条。
    public static JSONObject getManyShip(JSONObject obj) {
        JSONObject objRet = new JSONObject();
        String shipIds = JsonUtil.getJSONObjectString(obj, "shipIds");
        if(StringUtil.isEmpty(shipIds)) {
            objRet.put("msg","船舶id为空！");
            objRet.put("data", null);
            return objRet;
        }
        String url = ThirdConstant.GET_MANY_URL.replaceAll("key", ThirdConstant.KEY);
        String[] shipIdsArr = shipIds.split(",");
        JSONArray jsonArray = new JSONArray();
        if (shipIdsArr.length > 100) {
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < shipIdsArr.length; i++) {
                if (i%100 == 0 && i != 0) {
                    String reqUrl = null;
                    try {
                        reqUrl = url.replaceAll("shipIds",URLEncoder.encode(sb.substring(0,sb.length() - 1),"utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    objRet = HttpUtil.get(reqUrl);
                    jsonArray.addAll(JsonUtil.getJSONArray(objRet,"data"));
                    sb = new StringBuffer();
                }
                sb.append(shipIdsArr[i]).append(",");
            }
            if (sb.length() > 0) {
                String reqUrl = url.replaceAll("shipIds",sb.substring(0,sb.length() - 1));
                objRet = HttpUtil.get(reqUrl);
                jsonArray.addAll(JsonUtil.getJSONArray(objRet,"data"));
            }
            objRet = new JSONObject();
            objRet.put("data", jsonArray);
        }
        else {
            url = url.replaceAll("shipIds",shipIds);
            objRet.put("data", HttpUtil.get(url).getJSONArray("data"));
        }
        return objRet;
    }

    public static JSONObject getAreaShip(JSONObject obj) {
        JSONObject objRet = new JSONObject();
        String jinWei = JsonUtil.getJSONObjectString(obj, "jinWei");

        if(StringUtil.isEmpty(jinWei)) {
            objRet.put("msg","经纬度为空！");
            objRet.put("data", null);
            return objRet;
        }

        String reqUrl = ThirdConstant.GET_AREA_URL.replaceAll("jinWei",jinWei).replaceAll("key", ThirdConstant.KEY);
        objRet = HttpUtil.get(reqUrl);
        JSONObject retObj = new JSONObject();
        JSONArray jsonArray;
        jsonArray = objRet.getJSONArray("data");
        retObj.put("length",jsonArray.size());
        retObj.put("data", jsonArray);
        return retObj;
    }


    //船舶靠港记录
    public static JSONObject getPortOfCallByShip(JSONObject obj) throws Exception {
        JSONObject objRet = new JSONObject();
        String mmsi = JsonUtil.getJSONObjectString(obj,"mmsi");
        if (StringUtil.isEmpty(mmsi)) {
            objRet.put("msg","mmsi为空！");
            return null;
        }
        String begin = JsonUtil.getJSONObjectString(obj,"begin");
        String end = JsonUtil.getJSONObjectString(obj,"end");
        if (StringUtil.isEmpty(begin) || StringUtil.isEmpty(end)) {
            objRet.put("msg","开始，结束时间为空！");
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long beginDate = sdf.parse(begin).getTime()/1000;
        Long endDate = sdf.parse(end).getTime()/1000;
        String url = ThirdConstant.GET_PORT_OF_CALL_BY_SHIP_URL.replaceAll("key", ThirdConstant.KEY).replaceAll("MMSI",mmsi);
        url = url.replaceAll("BEGIN",beginDate.toString()).replaceAll("END",endDate.toString());
        objRet = HttpUtil.get(url);
        return objRet;
    }

    //船舶轨迹查询
    public static JSONObject getShipTrack(JSONObject obj) throws Exception {
        JSONObject objRet = new JSONObject();
        String mmsi = JsonUtil.getJSONObjectString(obj,"mmsi");
        if (StringUtil.isEmpty(mmsi)) {
            objRet.put("msg","mmsi为空！");
            return null;
        }
        String beginTime = JsonUtil.getJSONObjectString(obj,"begin");
        String endTime = JsonUtil.getJSONObjectString(obj,"end");
        if (StringUtil.isEmpty(beginTime) || StringUtil.isEmpty(endTime)) {
            objRet.put("msg","开始，结束时间为空！");
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long beginDate = sdf.parse(beginTime).getTime()/1000;
        Long endDate = sdf.parse(endTime).getTime()/1000;
        String url = ThirdConstant.GET_SHIP_TRACK_URL.replaceAll("key", ThirdConstant.KEY).replaceAll("MMSI",mmsi);
        url = url.replaceAll("BEGIN_TIME",beginDate.toString()).replaceAll("END_TIME",endDate.toString());
        objRet = HttpUtil.get(url);
        JSONArray jsonArray = objRet.getJSONArray("points");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            jsonObject.put("bj_time",DateUtil.getStandardTime(jsonObject.getLong("utc") * 1000 + 8*60*1000));
        }
        objRet.put("points", jsonArray);
        return objRet;
    }

    public static JSONObject updateShips(JSONObject obj) {
        String shipIds = JsonUtil.getJSONObjectString2(obj, "shipIds");
        String url = ThirdConstant.UPDATE_SHIPS1.replaceAll("key", ThirdConstant.KEY);
        Map<String, String> params = new HashMap<>();
        params.put("mmsis", shipIds);
        JSONObject objRet = HttpUtil.post(url, params);
        return objRet;
    }
}
